package com.projeto.web;

import com.projeto.business.controller.CustomerController;
import java.io.Serializable;
import java.util.List;

import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;

import com.projeto.business.controller.ReceiptController;
import com.projeto.business.controller.UserController;
import com.projeto.persistence.Customer;
import com.projeto.persistence.Customer.CustomerType;
import com.projeto.persistence.Receipt;
import com.projeto.persistence.Receipt.Status;
import com.projeto.persistence.ReceiptDetail;
import com.projeto.persistence.User;
import java.util.ArrayList;
import java.util.UUID;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import org.primefaces.context.RequestContext;

@ManagedBean
@SessionScoped
public class ReceiptBackBean implements Serializable {

    private List<Receipt> receiptList;
    private Receipt selectedReceipt = new Receipt();
    private ReceiptDetail selectedReceiptDetail = new ReceiptDetail();
    @EJB
    ReceiptController receiptBean;

    @EJB
    CustomerController customerBean;
    
    @EJB
    UserController userBean;
    
    private String consignee;
    private String shipper;
    private String receivedBy;
    //private String deliveredBy;
    private boolean hasInvoice;
    
    public Status[] getReceiptStatusValues() {
        return Receipt.Status.values();
    }
        
    public String getConsignee() {
        return consignee;
    }

    public void setConsignee(String consignee) {
        this.consignee = consignee;
    }

    public String getShipper() {
        return shipper;
    }

    public void setShipper(String shipper) {
        this.shipper = shipper;
    }

    public String getReceivedBy() {
        return receivedBy;
    }

    public void setReceivedBy(String receivedBy) {
        this.receivedBy = receivedBy;
    }

    //public String getDeliveredBy() {
    //    return deliveredBy;
    //}

    //public void setDeliveredBy(String deliveredBy) {
    //    this.deliveredBy = deliveredBy;
    //}
    
    
    public CustomerType[] getCustomerTypeValues() {
        return Customer.CustomerType.values();
    }
     
    public Receipt getSelectedReceipt() {
        return selectedReceipt;
    }

    public ReceiptDetail getSelectedReceiptDetail() {
        return selectedReceiptDetail;
    }

    public void setSelectedReceiptDetail(ReceiptDetail selectedReceiptDetail) {
        this.selectedReceiptDetail = selectedReceiptDetail;
    }

    public void setSelectedReceipt(Receipt selectedReceipt) {
        this.selectedReceipt = selectedReceipt;
    }

    public void addReceipt() {
        selectedReceipt = new Receipt();
    }
    
    public void addReceiptDetail() {
        selectedReceiptDetail = new ReceiptDetail();
        selectedReceiptDetail.setId(UUID.randomUUID().toString());
    }

    public List<Receipt> getReceiptList() {
        if (receiptList == null) {
            receiptList = receiptBean.findAll();
        }
        return receiptList;
    }

    public boolean isHasInvoice() {
        return hasInvoice;
    }

    public void setHasInvoice(boolean hasInvoice) {
        this.hasInvoice = hasInvoice;
    }

    public void reset() {
        receiptList = receiptBean.findAll();
        RequestContext.getCurrentInstance().update("form");
        RequestContext.getCurrentInstance().reset("frmDialog");
        //FacesContext.getCurrentInstance().getMessages().remove(); 
    }

    public List<String> searchShipper(String query)
    {
        return searchCustomer(query, CustomerType.SHIPPER);
    }
    
    public List<String> searchConsignee(String query)
    {
        return searchCustomer(query, CustomerType.CONSIGNEE);
    }    

    public List<String> searchUser(String query) {
        List<String> results = new ArrayList<String>();
          
        List<User> userList = userBean.findByName(query);
        if (userList != null && !userList.isEmpty())
        {
            for(User c : userList)
            {
                results.add(c.getName());
            }
        }

        return results;
    }
    
    private List<String> searchCustomer(String query, CustomerType type) {
        List<String> results = new ArrayList<String>();
          
        List<Customer> customerList = customerBean.findActiveByNameAndType(query, type);
        if (customerList != null && !customerList.isEmpty())
        {
            for(Customer c : customerList)
            {
                results.add(c.getFirstName());
            }
        }

        return results;
    }
        
    public void saveReceipt() {
        try {
            //@TODO add search funcionality into Receipt Screen
            //@TODO load the users by id and assign to receipt
            
            Customer s = customerBean.findActiveByNameAndType(shipper, CustomerType.SHIPPER).get(0);
            Customer c = customerBean.findActiveByNameAndType(consignee, CustomerType.CONSIGNEE).get(0);
            User r = userBean.find(receivedBy);
            selectedReceipt.setConsignee(c);
            selectedReceipt.setShipper(s);
            selectedReceipt.setReceivedBy(r);
            
            receiptBean.save(selectedReceipt);
            FacesContext.getCurrentInstance().addMessage("messages", new FacesMessage(FacesMessage.SEVERITY_INFO, "Receipt " + selectedReceipt.getNumber() + " Saved!", "Receipt saved"));

        } catch (Exception ex) {
            FacesContext.getCurrentInstance().addMessage("messages", new FacesMessage(FacesMessage.SEVERITY_ERROR, "Ocorreu um erro interno", "Receipt Not saved"));
        }
    }
    
    public void saveReceiptDetail() {
        try {
            //@TODO add search funcionality into Receipt Screen
            //@TODO load the users by id and assign to receipt
            
            //Customer c = customerBean.find(shipper);
            //User r = userBean.find(receivedBy);
            //selectedReceipt.setConsignee(c);
            //selectedReceipt.setShipper(c);
            //selectedReceipt.setDeliveredBy(c);
            //selectedReceipt.setReceivedBy(r);
            if (selectedReceipt.getReceiptDetails() == null || 
                    selectedReceipt.getReceiptDetails().isEmpty())
            {
                selectedReceipt.setReceiptDetails(new ArrayList<ReceiptDetail>());
            }
            selectedReceipt.getReceiptDetails().add(selectedReceiptDetail);
            
            Customer s = customerBean.findActiveByNameAndType(shipper, CustomerType.SHIPPER).get(0);
            Customer c = customerBean.findActiveByNameAndType(consignee, CustomerType.CONSIGNEE).get(0);            
            User r = userBean.find(receivedBy);
            selectedReceipt.setConsignee(c);
            selectedReceipt.setShipper(s);
            selectedReceipt.setReceivedBy(r);
            
            receiptBean.save(selectedReceipt);
            FacesContext.getCurrentInstance().addMessage("messages", new FacesMessage(FacesMessage.SEVERITY_INFO, "Receipt Detail " + selectedReceipt.getNumber() + " Saved!", "Receipt Detail saved"));

        } catch (Exception ex) {
            FacesContext.getCurrentInstance().addMessage("messages", new FacesMessage(FacesMessage.SEVERITY_ERROR, "Ocorreu um erro interno", "Receipt Detail Not saved"));
        }
    }
}
